package org.lep.leetcode.datastructure.hashtable;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * https://leetcode-cn.com/problems/valid-anagram/
 *
 * @author lverpeng
 * @since 2020/3/10
 */
public class ValidAnagram {
    /**
     * 按照字母序排序后比较是否相同
     * @param s
     * @param t
     * @return
     */
    public boolean isAnagram(String s, String t) {
        char[] sc = s.toCharArray();
        char[] tc = t.toCharArray();
        Arrays.sort(sc);
        Arrays.sort(tc);
        return Arrays.equals(sc, tc);
    }

    /**
     * 对出现的字母进行计数
     * @param s
     * @param t
     * @return
     */
    public boolean isAnagram1(String s, String t) {
        return buildMap(s).equals(buildMap(t));
    }

    private Map<Character, Integer> buildMap(String s) {
        Map<Character, Integer> sMap = new HashMap<>();
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (!sMap.containsKey(s.charAt(i))) {
                sMap.put(c, 1);
            } else {
                sMap.put(c, sMap.get(c) + 1);
            }
        }
        return sMap;
    }
}
